<template>
  <div class="product-filter" v-if="!filterVisit && !isMobile">
    <!-- 顶部 Filter & Sort -->
    <div class="filter-header" @click="closeFilter">
      <span class="filter-icon"><svg width="18" height="18" viewBox="0 0 18 18">
          <g stroke="currentColor" stroke-width="1.2" fill="none" fill-rule="evenodd">
            <path d="M2.5 4.5h13M5.5 9h7M8.5 13.5h1" stroke-linecap="round" />
          </g>
        </svg></span>
      <span class="filter-title">Filter & Sort</span>
      <span class="filter-close">×</span>
    </div>
    <!-- 清除所有选择 -->
    <div v-if="selectedTypes.length > 0">
      <span class="section-title">Refined By</span>
      <span class="clear-all" @click="clearAllFilter">Clear all</span>
      <div class="product-count">{{ props.totalCount }} results</div>
    </div>

    <!-- PRODUCT TYPE -->
    <div class="filter-section" v-for="item in props.collapseData.attributes" :key="item.classify_id">
      <div class="filter-section-header" @click="toggleCollapse(item.classify_id)">
        <span class="section-title">{{ item.classify_name }} <span v-if="selectedTypes.length" class="section-title">({{
          selectedTypes.length
            }})</span></span>
        <span class="collapse-arrow" :class="{ open: !showCategory[item.classify_id] }">
          <DownOutlined />
        </span>
      </div>
      <div v-show="!showCategory[item.classify_id]">
        <label v-for="value in item.values" :key="value.classify_value_id" class="category-item">
          <input type="checkbox" v-model="selectedTypes"
            :value="{ id: value.classify_value_id, name: value.classify_value_name, type: item.classify_name }"
            @change="handleFilterChange">
          <span class="category-name">{{ value.classify_value_name }}</span>
        </label>
        <!-- <a-checkbox-group v-model:value="selectedTypes" @change="handleFilterChange">
          <a-checkbox v-for="type in item.values" :key="type.classify_value_id" :value="{ id: type.classify_value_id, name: type.classify_value_name, type: item.classify_name }">{{
            type.classify_value_name }}</a-checkbox>
        </a-checkbox-group> -->
        <!-- <div class="show-all" @click="showAll('type')">Show All</div> -->
      </div>
    </div>

    <!-- COLOR -->
    <!-- <div class="filter-section">
      <div class="filter-section-header" @click="toggleCollapse('color')">
        <span class="section-title">COLOR <span v-if="selectedColors.length">({{ selectedColors.length
            }})</span></span>
        <span class="collapse-arrow" :class="{ open: !collapsed.color }">
          <DownOutlined />
        </span>
      </div>
      <div v-show="!collapsed.color">
        <div class="color-options">
          <span v-for="color in colors" :key="color.value" :style="{ background: color.value }" class="color-dot"
            @click="toggleColor(color.value)" :class="{ active: selectedColors.includes(color.value) }"></span>
        </div>
        <div class="color-labels">
          <span v-for="color in colors" :key="color.value + '-label'" class="color-label"
            :style="{ color: color.value === '#fff' ? '#888' : color.value }">{{ color.label }}</span>
        </div>
      </div>
    </div> -->

    <!-- SIZE -->
    <!-- <div class="filter-section">
      <div class="filter-section-header" @click="toggleCollapse('size')">
        <span class="section-title">SIZE<span v-if="selectedSizes.length"> ({{ selectedSizes.length }})</span></span>
        <span class="collapse-arrow" :class="{ open: !collapsed.size }">
          <DownOutlined />
        </span>
      </div>
      <div v-show="!collapsed.size">
        <div class="size-btn-group">
          <button v-for="size in sizes" :key="size" :class="['size-btn', { active: selectedSizes.includes(size) }]"
            @click="toggleSize(size)">{{ size }}</button>
        </div>
      </div>
    </div> -->
  </div>
  <!-- Mobile filter panel -->
  <div class="mobile-filter-panel" v-if="isMobile">
    <div class="mobile-filter-section" v-for="item in props.collapseData.attributes" :key="item.classify_id">
      <h3>{{ item.classify_name }}</h3>
      <div class="category-list">
        <label v-for="value in item.values" :key="value.classify_value_id" class="category-item">
          <input type="checkbox" v-model="selectedTypes"
            :value="{ id: value.classify_value_id, name: value.classify_value_name, type: item.classify_name }"
            @change="handleFilterChange">
          <span class="category-name">{{ value.classify_value_name }}</span>
        </label>
      </div>
    </div>

    <div class="mobile-filter-actions">
      <button class="apply-filters" @click="applyFilters">Apply Filters</button>
      <button class="clear-filters" @click="clearAllFilters">Clear All</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { DownOutlined } from '@ant-design/icons-vue';

const props = defineProps<{
  totalCount: number;
  collapseData: any;
}>();
const colors = [
  { label: 'Red', value: '#e10613' },
  { label: 'White', value: '#fff' },
  { label: 'Beige', value: '#f8f6e7' },
  { label: 'Grey', value: '#d6d6d6' },
  { label: 'Yellow', value: '#ffe600' },
  { label: 'Black', value: '#19191a' },
  { label: 'Brown', value: '#7a4a1d' },
  { label: 'Camel', value: '#d2b48c' },
  { label: 'Khaki', value: '#c3a47d' },
  { label: 'Green', value: '#00724c' },
];
const sizes = ['XXS', 'XS', 'S', 'M', 'L', 'XL', 'XXL', '24', '25', '26'];
const emits = defineEmits(['handleShow', 'filter-change','closeMobileFilter'])

const selectedTypes = ref([]);
const selectedColors = ref([]);
const selectedSizes = ref([]);

// const collapsed = ref({ type: false, color: false, size: false });
// 展开/收起状态
const showCategory = ref<{ [key: string]: boolean }>({});
function toggleCollapse(key: string) {
  showCategory.value[key] = !showCategory.value[key];
}
function showAll(key) { /* 可扩展为弹窗或全部展开 */ }
const filterVisit = ref(false)
// 关闭左边的条件筛选
function closeFilter() {
  filterVisit.value = !filterVisit.value
  emits('handleShow')
}
function toggleColor(color) {
  if (selectedColors.value.includes(color)) {
    selectedColors.value = selectedColors.value.filter(c => c !== color);
  } else {
    selectedColors.value.push(color);
  }
}
function toggleSize(size) {
  if (selectedSizes.value.includes(size)) {
    selectedSizes.value = selectedSizes.value.filter(s => s !== size);
  } else {
    selectedSizes.value.push(size);
  }
}

const handleFilterChange = (event?: Event) => {
  // 收集所有选中的筛选条件
  const selectedFilters = selectedTypes.value;
  emits('filter-change', selectedFilters);

};
// 清除所有选择
const clearAllFilter = () => {
  selectedTypes.value = []
  emits('filter-change', selectedTypes.value);
}

const applyFilters = () => {
  const selectedFilters = selectedTypes.value;
  localStorage.setItem('selectedFilters', JSON.stringify(selectedFilters));
  emits('filter-change', selectedFilters);
  emits('closeMobileFilter');
};
// 清除所有筛选
const clearAllFilters = () => {
  selectedTypes.value = [];
  emits('filter-change', selectedTypes.value);
  localStorage.removeItem('selectedFilters');
  
};
const isMobile = ref(false)        // 是否为移动端
/**
 * 检查当前设备是否为移动端
 * 根据窗口宽度判断（<=768px 为移动端）
 */
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}
// 在组件挂载时记录初始位置
onMounted(() => {
  // 初始检查设备类型
  checkMobile();
  // 从localStorage读取保存的筛选值
  const savedFilters = localStorage.getItem('selectedFilters');
  if (savedFilters) {
    selectedTypes.value = JSON.parse(savedFilters);
    // 触发筛选变化事件
    emits('filter-change', selectedTypes.value);
  }
})
</script>

<style scoped>
.category-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  padding-bottom: 6px;
  font-size: 12px;
  color: #232323;

  input[type="checkbox"] {
    margin: 0;
    width: 16px;
    height: 16px;
    cursor: pointer;
    accent-color: #000;
  }

  .category-count {
    color: #666;
  }
}

.product-filter {
  width: 300px;
  background: #fff;
  padding: 20px 16px 0 16px;
  border-radius: 4px;
  margin-right: 60px;
}

.filter-header {
  display: flex;
  align-items: center;
  border: 1px solid #ccc;
  border-radius: 2px;
  padding: 4px 12px;
  margin-bottom: 34px;
  font-size: 16px;
  position: relative;
}

.filter-icon {
  margin-right: 8px;
  color: #222;
}

.filter-title {
  flex: 1;
  font-weight: 500;
  color: #3D3D3D;
  font-size: 14px;
}

.filter-close {
  font-size: 22px;
  color: #888;
  cursor: pointer;
  margin-left: 8px;
}

.filter-section {
  margin-bottom: 32px;

}

.filter-section-header {
  display: flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  border-bottom: 1px solid #787878;
  padding-bottom: 6px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
  color: #232323;
  flex: 1;

}

.collapse-arrow {
  font-size: 12px;
  color: #888;
  transition: transform 0.2s;
  margin-left: 8px;
  transform: rotate(180deg);
}

.collapse-arrow.open {
  transform: rotate(0deg);
}

.divider {
  border-bottom: 2px solid #e5e5e5;
  margin: 8px 0 16px 0;
}

.show-all {
  color: #222;
  font-size: 14px;
  margin-top: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
}

.color-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 16px;
  margin-bottom: 8px;
}

.color-dot {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1.5px solid #ccc;
  cursor: pointer;
  display: inline-block;
  box-sizing: border-box;
  transition: border 0.2s;
}

.color-dot.active {
  border: 2.5px solid #19191a;
}

.color-labels {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 16px;
  margin-bottom: 4px;
  font-size: 13px;
  color: #222;
}

.color-label {
  width: 40px;
  text-align: left;
  margin-right: 2px;
}

.size-btn-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 12px;
  margin-bottom: 8px;
}

.size-btn {
  min-width: 50px;
  height: 30px;
  border: 1px solid #dadada;
  background: #fff;
  color: #232323;
  font-size: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: border 0.2s, background 0.2s, color 0.2s;
  outline: none;
}

.size-btn.active {
  border: 1px solid #232323;
  background: #f5f5f5;
  color: #000;
  /* font-weight: 600; */
}

.size-btn:active {
  background: #ececec;
}

.clear-all {
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.5px;
  color: #3c3c3c;
  flex: 1;
  text-decoration: underline;
  margin-left: 125px;
  cursor: pointer;
}

.product-count {
  font-size: 12px;
  color: #707070;
  padding-top: 5px;
  margin-bottom: 15px;
}

.mobile-filter-panel {
  position: fixed;
  left: 0;
  width: 100%;
  height: 100%;
  background: white;
  z-index: 1001;
  overflow-y: auto;
  padding: 20px 20px 120px 20px;
}

.mobile-filter-section {
  margin-bottom: 24px;

  h3 {
    font-size: 16px;
    margin-bottom: 15px;
  }
}

.category-list {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px 15px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 5px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;

  input[type="checkbox"] {
    margin: 0;
    width: 16px;
    height: 16px;
    cursor: pointer;
  }

  .category-count {
    color: #666;
  }
}
.mobile-filter-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 15px;
  background: white;
  border-top: 1px solid #e8e8e8;
  display: flex;
  gap: 10px;

  button {
    flex: 1;
    padding: 12px;
    border: 1px solid #000;
    font-weight: 500;
    cursor: pointer;

    &.apply-filters {
      background: #000;
      color: white;
    }

    &.clear-filters {
      background: white;
      color: #000;
    }
  }
}
:deep(:where(.css-dev-only-do-not-override-12unj27).ant-checkbox-group) {
  /* box-sizing: border-box; */
  margin: 0;
  padding: 0;
  color: rgba(0, 0, 0, 0.88);
  font-size: 14px;
  line-height: 1.5714285714285714;
  list-style: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  display: inline-flex;
  flex-wrap: wrap;
  column-gap: 160px;
}

:deep(:where(.css-dev-only-do-not-override-12unj27).ant-checkbox-wrapper) {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  color: rgba(0, 0, 0, 0.88);
  font-size: 14px;
  line-height: 2;
  list-style: none;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
  display: inline-flex;
  align-items: baseline;
  cursor: pointer;
}
</style>